package netty.demo.nio.selector;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

import static netty.demo.nio.byteBuffer.ByteBufferUtil.debugRead;


/**
 * @author Zed
 * @description
 * @date 2022/10/23 10:13
 */
@Slf4j
public class Server {
    @SneakyThrows
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1.创建了服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);//非阻塞模式
        //2.绑定监听端口
        ssc.bind(new InetSocketAddress(8080));
        //3.连接集合
        ArrayList<SocketChannel> channelList = new ArrayList<>();
        while (true) {
            //4.accept 建立与客户端连接,socketChannel用来与客户端之间通信
            System.out.println("connecting...");
            /**
             *             阻塞方法,线程停止运行
             *             非阻塞,线程会继续运行，如果没有连接建立，但sc是null
             */
            SocketChannel sc = ssc.accept();
            if (sc != null) {
                System.out.println("connected..." + sc);
                //非阻塞模式， channel.read(buffer)方法也会变成非阻塞方法，线程仍然会继续运行，如果没有读到数据，read返回0
                sc.configureBlocking(false);
                channelList.add(sc);
            }
            for (SocketChannel channel : channelList) {
                //5.接收客户端发送的数据
                System.out.println("before read..." + channel);
                int readCount = channel.read(buffer);//阻塞方法，线程停止运行
                if (readCount > 0) {
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    System.out.println("after read..." + channel);
                }
            }
        }
    }
}
